package com.hzit.listener;

import com.hzit.entity.Product;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;
import java.util.ArrayList;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebListener
public class MyApplicationListener implements ServletContextListener, ServletContextAttributeListener {

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//1. 获取应用程序对象
		ServletContext servletContext = sce.getServletContext();
		//2. 定义商品对象
		Product p1 = new Product(1001,"海尔洗衣机",2000.0,10);
		Product p2 = new Product(1002,"洽洽瓜子",5.0,100);
		Product p3 = new Product(1003,"海飞丝洗发水",30.0,500);
		Product p4 = new Product(1004,"双飞燕鼠标",20.0,600);
		Product p5 = new Product(1005,"联想电脑",5000.0,40);
		Product p6 = new Product(1006,"华为手机",6000.0,50);
		Product p7 = new Product(1007,"格力空调",4000.0,40);
		Product p8 = new Product(1008,"红木家具",20000.0,20);
		//3. 定义集合用于存放商品
		List<Product> products = new ArrayList<>();
		products.add(p1);
		products.add(p2);
		products.add(p3);
		products.add(p4);
		products.add(p5);
		products.add(p6);
		products.add(p7);
		products.add(p8);
		//4. 将集合放到servletContext中
		servletContext.setAttribute("products",products);

	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("application 被销毁.");
	}

	// application.setAttribute()时触发
	@Override
	public void attributeAdded(ServletContextAttributeEvent event) {
		System.out.println("为application设置属性值。");
	}
	// application.removeAttribute()时触发
	@Override
	public void attributeRemoved(ServletContextAttributeEvent event) {
		System.out.println("为application删除改属性值。");
	}

	@Override
	public void attributeReplaced(ServletContextAttributeEvent event) {

	}

}
